<template>
  <div ref="chart" :class="className" :style="{ 'height': height, 'width': width }" ></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts'
import { PropType } from "vue";
import { debounce } from "lodash-es";
const chart = ref(null)
let customECharts: echarts.ECharts  = null!

const props = defineProps({
  className: {
    type: String ,
    default: '',
  },
  height: {
    type: String,
    default: '100%',
  },
  width: {
    type: String,
    default: '100%',
  },
  options: {
    type: Object as PropType<EChartsOption>,
    required: true,
    default: {}
  },
});

onMounted(()=>{
  initEChats()
})

const resizeHandler = debounce(()=>{
  customECharts.resize()
},100)

function initEChats(){
  customECharts = echarts.init(chart.value as HTMLElement)
  customECharts.setOption(props.options!)
  //随着屏幕大小调节图表
  window.addEventListener("resize", resizeHandler);
}

watchEffect(() => {
  if (props.options && customECharts){
    customECharts.setOption(props.options!)
  }
})

onActivated(() => {
  if (customECharts) {
    customECharts.resize()
  }
})

onBeforeUnmount(()=>{
  window.removeEventListener('resize', resizeHandler)
})
</script>

<style scoped lang="scss">

</style>